package com.mazaiting.redeye.module.me

import android.text.TextUtils
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.api.BasicCallback
import com.mazaiting.easy.base.bean.BaseBean
import com.mazaiting.easy.base.bean.Response
import com.mazaiting.easy.base.mvp.IBaseView
import com.mazaiting.easy.utils.rx.RxScheduler
import com.mazaiting.log.L
import com.mazaiting.redeye.api.UserApi
import com.mazaiting.redeye.base.ApplicationComponentImpl
import com.mazaiting.redeye.base.BaseCommonPresenter
import com.mazaiting.redeye.base.CustomConsumer
import com.mazaiting.redeye.base.ICancelPresenter
import com.mazaiting.redeye.bean.ImageBean
import com.mazaiting.redeye.bean.Request
import com.mazaiting.redeye.bean.UserBean
import com.mazaiting.redeye.bean.VerifyCodeBean
import com.mazaiting.redeye.utils.ErrorCodeUtil
import com.trello.rxlifecycle3.kotlin.bindToLifecycle
import dagger.Component
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import java.io.File
import javax.inject.Inject

/***
 *
 *
 *                                                    __----~~~~~~~~~~~------___
 *                                   .  .   ~~//====......          __--~ ~~
 *                   -.            \_|//     |||\\  ~~~~~~::::... /~
 *                ___-==_       _-~o~  \/    |||  \\            _/~~-
 *        __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
 *    _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
 *  .~       .~       |   \\ -_    /  /-   /   ||      \   /
 * /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 * |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
 *          '         ~-|      /|    |-~\~~       __--~~
 *                      |-~~-_/ |    |   ~\_   _-~            /\
 *                           /  \     \__   \/~                \__
 *                       _--~ _/ | .-~~____--~-/                  ~~==.
 *                      ((->/~   '.|||' -_|    ~~-/ ,              . _||
 *                                 -_     ~\      ~~---l__i__i__i--~~_/
 *                                 _-~-__   ~)  \--______________--~~
 *                               //.-~~~-~_--~- |-------~~~~~~~~
 *                                      //.-~~~--\
 *                               神兽保佑
 *                              代码无BUG!
 * @author mazaiting
 * @date 2019-07-01
 * @description 头像联系人
 */
class AvatarContract {
    interface View : IBaseView {
        /**
         * 上传成功
         * @param imageBean 图像信息
         */
        fun uploadSuccess(imageBean: ImageBean)

        /**
         * 上传失败
         */
        fun uploadError(msg: String)

        /**
         * 更新头像成功
         */
        fun updateAvatarSuccess()

        /**
         * 更新头像失败
         * @param msg 消息
         */
        fun updateAvatarError(msg: String)
    }
    interface Presenter : ICancelPresenter<View> {
        /**
         * 上传图片
         * @param imagePath 图片路径
         */
        fun uploadImage(imagePath: String?)

        /**
         * 更新手机号
         * @param verifyCodeBean 验证码实体
         */
        fun updatePhone(verifyCodeBean: VerifyCodeBean<UserBean>)

        /**
         * 更新用户头像
         */
        fun updateAvatar(imagePath: String?)
    }
}

/**
 * 头像主持人
 */
class AvatarPresenter
@Inject constructor(
    private val userApi: UserApi
) : BaseCommonPresenter<AvatarContract.View>(), AvatarContract.Presenter {
    override fun updateAvatar(imagePath: String?) {
        if (TextUtils.isEmpty(imagePath)) {
            view.updateAvatarError("图片不能为空")
            return
        }
        // 更新用户头像
        JMessageClient.updateUserAvatar(File(imagePath), object :BasicCallback(){
            override fun gotResult(code: Int, msg: String) {
                L.d("code: $code, msg: $msg")
                if (0 == code) {
                    view.updateAvatarSuccess()
                } else {
                    view.updateAvatarError(ErrorCodeUtil.getMessage(code))
                }
            }
        })
    }

    /**
     * 上传图片 Disposable
     */
    private var mUploadDispose: Disposable? = null
    /**
     * 更新手机号 Disposable
     */
    private var mUpdatePhoneDispose: Disposable? = null

    override fun uploadImage(imagePath: String?) {
        if (isNetConnected) {
            // 检测图片图片路径是否为空
            if (!TextUtils.isEmpty(imagePath)) {
                view.onShowLoading()
                mUploadDispose = userApi.uploadImage(imagePath!!)
                    .compose(RxScheduler.applySchedulers())
                    .bindToLifecycle(view.lifecycleProvider)
                    .subscribe(object : CustomConsumer<Response<List<ImageBean>>> {
                        override fun onSuccess(result: Response<List<ImageBean>>?) {
                            if (null != result) {
                                if (result.retCode == 1) {
                                    // 请求成功
                                    view.onShowSuccess()
                                    // 上传成功
                                    view.uploadSuccess(result.data[0])
                                } else {
                                    view.onShowFailed(result.msg)
                                    view.uploadError(result.msg)
                                }
                            } else {
                                view.onShowFailed(result?.msg)
                                view.uploadError("请求失败")
                            }
                        }
                    }, Consumer<Throwable> { e ->
                        L.d(e.message)
                        e.message?.let { view.uploadError(it) }
                        view.onShowFailed(e.message)
                    })
            } else {
                view.onShowFailed("图片路径不能为空")
            }
        } else {
            view.onShowNoNet()
        }
    }


    override fun updatePhone(verifyCodeBean: VerifyCodeBean<UserBean>) {
        // 设置用户名
        verifyCodeBean.data.username = username
        mUpdatePhoneDispose =
            userApi.updatePhone(Request(token, verifyCodeBean))
                .compose(RxScheduler.applySchedulers())
                .bindToLifecycle(view.lifecycleProvider)
                .subscribe(object : CustomConsumer<BaseBean> {
                    override fun onSuccess(result: BaseBean?) {
                        L.d(result?.toString())
                    }

                }, Consumer<Throwable> { e -> L.d(e.message) })
    }

    override fun cancel() {
        mUploadDispose?.dispose()
        mUpdatePhoneDispose?.dispose()
    }

}

/**
 * 头像组件
 */
@Component(dependencies = [ApplicationComponentImpl::class])
interface AvatarComponent {
    /**
     * 注入头像界面
     * @param activity 页面
     */
    fun inject(activity: AvatarActivity)
}